<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <PageTools :show-before="false">
        <template v-slot:after>
          <el-button type="primary" size="small" @click="addFn('0',1)">添加权限</el-button>
        </template>
      </PageTools>
      <!-- 表格 -->
      <!-- 渲染树形结构条件：
      1.数据中必须包括children属性
      2.row-key：优化表格渲染，用于告诉表格组件我们的数据中Id属性是唯一的值-->
      <el-table row-key="id" :data="permissionList" border>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="code" label="标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button v-if="row.pid === '0'" type="text" @click="addFn(row.id,2)">添加</el-button>
            <el-button type="text" @click="ediFn(row.id)">编辑</el-button>
            <el-button type="text" @click="delFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增权限 -->
      <AddPerm ref="addPerm" :show-dialog.sync="visibleDialog" @updateEvent="getPermissionList" />
    </div>
  </div>
</template>

<script>
import { listToTree } from '@/utils/index'
import { getPermissions, delPermission } from '@/api/permission'
import AddPerm from './components/add-permission.vue'
export default {
  components: {
    AddPerm
  },
  data() {
    return {
      permissionList: [],
      visibleDialog: false
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 编辑权限
    async ediFn(id) {
      this.visibleDialog = true
      // 通过ref获取到子组件实例，然后调用获取详情函数
      this.$refs.addPerm.getPermissionDetail(id)
    },
    // 删除权限
    delFn(id) {
      this.$confirm('确认删除该权限？', '提示', {
        type: 'warning'
      }).then(async() => {
        // 点击确认，调用接口
        await delPermission(id)
        // 刷新权限列表
        this.getPermissionList()
      }).catch(() => {
        console.log('点击了取消按钮')
      })
    },
    // 添加权限
    addFn(pid, type) {
      this.visibleDialog = true
      // 通过ref获取到子组件实例，然后把pid和type的值赋值给子组件的form里面的pid和type
      // console.log(this.$refs.addPerm)
      this.$refs.addPerm.formData.pid = pid
      this.$refs.addPerm.formData.type = type
    },
    // 获取所有权限点
    async getPermissionList() {
      const res = await getPermissions()
      // 把列表转为树形结构
      this.permissionList = listToTree(res, '0')
    }
  }
}
</script>

<style scoped>
.el-table{
  margin-top: 20px;
}
</style>
